<?php


// error_reporting(1);

/* 
URL:  xxxx?site=site1
postMan   application/json   raw  {"password":"test" } 
gitee.com    密码： test

*/
#open file
$file = fopen("webhook.log","a");


$arr = json_decode(file_get_contents('php://input'),true);

#test
// fwrite($file, date('Y-m-d H:i:s')."] ".json_encode($arr)." \r\n");
// fwrite($file, date('Y-m-d H:i:s')."] ".json_encode(@$_SERVER['HTTP_X_HUB_SIGNATURE'])." \r\n");

$site = $_GET['site'];
fwrite($file, date('Y-m-d H:i:s')."] $site \r\n");

$target = '/www/'.$site;

$token = getPwd($site);


// fwrite($file, date('Y-m-d H:i:s')."] ".json_encode($arr)." \r\n");


if (@$arr['password']) {  # gitee
    if($arr['password'] != $token){
        fwrite($file, "password error \r\n");
        fclose($file);
        exit('error request');
    }
} elseif( $headerSignature = @$_SERVER['HTTP_X_HUB_SIGNATURE'] ) { #github
    $signature = 'sha1=' . hash_hmac('sha1', file_get_contents('php://input'), $token); 

    if ( !hash_equals($signature, $headerSignature)) {  
        fwrite($file, date('Y-m-d H:i:s')."] github-check-error \r\n");
        fclose($file);
        exit('check-error');
    } 

}

// fclose($file);
// echo 'ok';
// exit;



#  git 
$cmd1=" cd $target ; sudo -Hu www git pull 2>&1";

$res1 = shell_exec($cmd1);


fwrite($file, date('Y-m-d H:i:s')."] $res1 \r\n");


# migrate
if ($site == 'blog55') {
    $cmd2 = "cd $target;  sudo -u www php artisan migrate";
    $res2 = shell_exec($cmd2);

    fwrite($file, date('Y-m-d H:i:s')."] $res2 \r\n");

    // $cmd3 = "cd $target;  sudo -Hu www php composer.phar install";
    // $res3 = shell_exec($cmd3);

}


#close file
if($file) {
	fclose($file);
}

echo 'ok';




if ($res1) {
    echo 'command exec success';
} else {
    echo 'exec error';
}




function getPwd($site) {

    switch($site) {
        case 'blog55':
            return 'b51175abC123';
            break;
        case 'test_php':
            return 'tp123JI345';
            break;
    }
}

